<template>
  <div class="container margin-top-10">
    <div class="row">
      <!-- 左侧 -->
      <div class="col-8">
        <blog-item
          :blog="blog"
          :key="blog.id"
          v-for="blog in blogs"
        />
        <div class="loading-more">{{loadingText}}</div>
      </div>
      <!-- 右侧 -->
      <div class="col-4"></div>
      <!-- 右侧结束 -->
    </div>
  </div>
</template>

<script>
import { ref } from "vue";

import { getFocusBlogs } from "../../network/blog";
import debounce from '../../utils/debounce'
import BlogItem from "../../components/blog-item/BlogItem";
export default {
  name: "Focus",
  components: { BlogItem },
  setup() {
    const blogs = ref(null);
    const currentPage = ref(1);
    const loadingText = ref("加载更多……");
    const windowHeight = ref(
      document.documentElement.clientHeight || document.body.clientHeight
    ); //视口高度

    //滚动到底部加载更多事件
    const listenToScroll = () => {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

      if (scrollTop + windowHeight.value > scrollHeight - 100) {
        loadingText.value === "加载更多……" && gainFocusBlogs(currentPage.value);
      }
    };

    //监听滚动事件
    window.addEventListener("scroll", debounce(listenToScroll, 200));

    //获取微博
    const gainFocusBlogs = async (page) => {
      const result = await getFocusBlogs({ page, limit: 5 });
      // console.log(result);
      if (result.status !== 200) {
        return console.log(result.message);
      }
      currentPage.value = result.data.page + 1;
      blogs.value =
        page === 1
          ? result.data.result
          : [...blogs.value, ...result.data.result];
      loadingText.value =
        result.data.result.length < 5 ? "已加载全部~" : "加载更多……";
    };
    gainFocusBlogs(currentPage.value);

    return {
      blogs,
      loadingText,
      currentPage,
    };
  },
};
</script>

<style scoped lang='stylus' >
.loading-more
  margin 10px 0
  text-align center
</style>